package com.example.OneToOne.service;

import com.example.OneToOne.entity.Author;
import com.example.OneToOne.entity.Book;
import com.example.OneToOne.repository.AuthorRepository;
import com.example.OneToOne.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AuthorAndBookImpl implements AuthorAndBookService{
    @Autowired
    private BookRepository bookRepository;
    @Autowired
    private AuthorRepository authorRepository;
    @Override
    public void saveAll(){
        Book book1=new Book();
        book1.setName("红楼梦");
        Book book2=new Book();
        book2.setName("西游记");
        Book book3=new Book();
        book3.setName("水浒传");
        List<Book> books=new ArrayList<Book>();
        books.add(book1);
        books.add(book2);
        books.add(book3);
        bookRepository.saveAll(books);
        Author author1=new Author();
        author1.setName("曹雪芹");
        author1.setAge(16);
        author1.setBookName("红楼梦");
        author1.setBook(book1);
        Author author2=new Author();
        author2.setName("吴承恩");
        author2.setAge(17);
        author2.setBookName("西游记");
        author2.setBook(book2);
        Author author3=new Author();
        author3.setName("施耐庵");
        author3.setAge(18);
        author3.setBookName("水浒传");
        author3.setBook(book3);
        List<Author> authors=new ArrayList<Author>();
        authors.add(author1);
        authors.add(author2);
        authors.add(author3);
        authorRepository.saveAll(authors);
    }
    @Override
    public List<Author> findAllAuthor(){
        return authorRepository.findAll();
    }
    @Override
    public List<Book> findAllBook(){
        return bookRepository.findAll();
    }
    @Override
    public Author findByBook_id(int id){
        return authorRepository.findByBook_id(id);
    }
    @Override
    public Book findByAuthor_id(int id){
        return bookRepository.findBookByAuthor_id(id);
    }
    @Override
    public Book getOneBook(int id){
        return bookRepository.getById(id);
    }
    @Override
    public Author getOneAuthor(int id){
        return authorRepository.getById(id);
    }
    @Override
    public String delByAuthorId(int id){
        authorRepository.deleteById(id);
        return "删除作者成功";
    }
    @Override
    public Author updateAuthorById(int id,Author author){
        Author existingAuthor = authorRepository.getById(id);
        if (existingAuthor != null) {
            existingAuthor.setName(author.getName());
            existingAuthor.setBookName(author.getBookName());
            existingAuthor.setAge(author.getAge());
            existingAuthor.setId(author.getId());
            return authorRepository.save(existingAuthor);
        }
        return null;
    }
}
